package cn.com.netedge.iot.frontend.biz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
/**
 * springboot配置线程池  参考：https://blog.csdn.net/Arvinzr/article/details/88926978
 */
public class ExecutorConfig {

    @Bean
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(10);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(99999);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");
        /**任务拒绝处理策略：
         * CallerRunsPolicy：不进入线程池执行，在这种方式中任务将有调用者线程去执行
         * DiscardPolicy：丢弃当前将要加入队列的任务本身
         * DiscardOldestPolicy：丢弃任务队列中最旧任务
         * AbortPolicy：抛出异常RuntimeException，会中断调用者的处理过程
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setAwaitTerminationSeconds(60);// 线程池关闭前最大等待时间，确保最后一定关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);// 线程池关闭时等待所有任务完成
        executor.initialize();
        return executor;
    }
}
